{% extends 'home.html' %}

{% block content %}
    <div class="container mt-4">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2 class="mb-0">工具管理系统</h2>
            <!-- 添加工具按钮 -->
            <button type="button" class="btn btn-primary"
                    data-bs-toggle="modal"
                    data-bs-target="#toolModal"
                    onclick="addTool()">
                <i class="bi bi-plus-circle me-2"></i> 添加工具
            </button>
        </div>

        <!-- 工具模态框 -->
        <div class="modal fade" id="toolModal" tabindex="-1" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">
                            <i class="bi bi-tools me-2"></i>
                            {% if tool_id %}编辑工具{% else %}添加新工具{% endif %}
                        </h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <form id="toolForm" method="post" action="{% url 'tool_manage' %}">
                            {% csrf_token %}
                            <input type="hidden" name="tool_id" id="tool_id" value="">
                            {% if form.errors %}
                                <div class="alert alert-danger">
                                    {% for field, errors in form.errors.items %}
                                        {% for error in errors %}
                                            <p>{{ error }}</p>
                                        {% endfor %}
                                    {% endfor %}
                                </div>
                            {% endif %}
                            {{ form.as_p }}
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                                <button type="button" name="submitBtn" class="btn btn-primary">保存</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <!-- 工具列表 -->
        <div class="card">
            <div class="card-header">
                <h4 class="mb-0">
                    <i class="bi bi-tools me-2"></i>
                    工具列表
                </h4>
            </div>

            <div class="card-body p-0">
                {% if tools %}
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                            <tr>
                                <th>名称</th>
                                <th>编码</th>
                                <th>型号</th>
                                <th>类别</th>
                                <th class="text-end">操作</th>
                            </tr>
                            </thead>
                            <tbody>
                            {% for tool in tools %}
                                <tr>
                                    <td>{{ tool.title }}</td>
                                    <td>{{ tool.tool_number }}</td>
                                    <td>{{ tool.certificate_number }}</td>
                                    <td>{{ tool.end_date }}</td>
                                    <td class="text-end">
                                        <div class="btn-group" role="group">
                                            <button type="button" class="btn btn-sm btn-primary"
                                                    onclick="editTool('{{ tool.tool_number }}')">
                                                <i class="bi bi-pencil me-2"></i>编辑
                                            </button>
                                            <button class="btn btn-sm btn-danger"
                                                    onclick="confirmDelete('{{ tool.tool_number }}')">
                                                <i class="bi bi-trash me-2"></i>删除
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                            {% endfor %}
                            </tbody>
                        </table>
                    </div>
                {% else %}
                    <div class="alert alert-info m-4">
                        <i class="bi bi-info-circle me-2"></i>
                        暂时没有工具记录，点击右上角按钮添加新工具
                    </div>
                {% endif %}
            </div>
        </div>
    </div>
{% endblock %}

{% block js %}
    <script>
        function addTool() {
            $('#tool_id').val('');
            $('#toolModal .modal-title').text('添加新工具');
            $('form').attr('action', "{% url 'tool_manage' %}");
            $('#toolModal').modal('show');
        }

        function editTool(toolNumber) {
            $('#tool_id').val(toolNumber);
            $('#toolModal .modal-title').text('编辑工具');
            
            console.log('Attempting to edit tool:', toolNumber);
            
            // 清除之前的错误提示和表单数据
            $('#toolModal').find('.alert-danger').remove();
            $('#toolForm')[0].reset();
            
            // 添加加载状态提示
            $('#toolModal').find('.modal-body').prepend(
                '<div class="alert alert-info" id="loadingAlert">正在加载工具数据...</div>'
            );
            
            $.ajax({
                url: "{% url 'tool_manage' %}",
                type: "GET",
                data: { tool_id: toolNumber },
                dataType: 'json',
                success: function(data) {
                    $('#loadingAlert').remove();
                    
                    console.log('Received data:', data);
                    
                    if(!data || data.success === false) {
                        showErrorAlert(data && data.message ? data.message : '获取工具数据失败');
                        $('#toolModal').modal('show');
                        return;
                    }
                    
                    try {
                        // 改进表单字段填充逻辑
                        let fieldsFilled = 0;
                        for (let key in data) {
                            if (key === 'success' || key === 'message') continue;
                            
                            // 尝试匹配多种可能的字段ID形式
                            let selector = `#id_${key}, #${key}, [name="${key}"], [name=${key}]`;
                            let $field = $(selector);
                            
                            console.log(`Searching field for ${key} with selector: ${selector}`);
                            
                            if ($field.length > 0) {
                                console.log(`Found field for ${key}:`, $field);
                                
                                if ($field.is('select')) {
                                    $field.val(data[key]).trigger('change');
                                } else if ($field.is(':checkbox')) {
                                    $field.prop('checked', data[key]);
                                } else {
                                    $field.val(data[key]);
                                }
                                fieldsFilled++;
                            } else {
                                console.warn(`Form field not found for key: ${key}`, data[key]);
                                $('#toolModal').find('.modal-body').append(
                                    `<div class="alert alert-warning">字段 ${key} 未找到，值: ${data[key]}</div>`
                                );
                            }
                        }
                        
                        console.log(`Filled ${fieldsFilled} fields successfully`);
                        
                        // 确保所有字段填充后再显示模态框
                        $('#toolModal').modal('show');
                        $('#toolModal').modal('handleUpdate');
                        
                    } catch(e) {
                        console.error('Form field update error:', e);
                        showErrorAlert('表单更新失败: ' + e.message);
                        $('#toolModal').modal('show');
                    }
                },
                error: function(xhr) {
                    $('#loadingAlert').remove();
                    handleAjaxError(xhr);
                    $('#toolModal').modal('show');
                }
            });
        }

        // 增强错误处理函数
        function handleAjaxError(xhr) {
            console.error('AJAX Error:', xhr);
            let errorMsg = '服务器错误 (' + xhr.status + ')';
            
            try {
                let response = JSON.parse(xhr.responseText);
                errorMsg = response.message || errorMsg;
                if(response.error) errorMsg += ': ' + response.error;
                if(response.detail) errorMsg += ': ' + response.detail;
                
                // 处理CSRF token失效的情况
                if(xhr.status === 403 && response.detail === 'CSRF Failed: CSRF token missing or incorrect.') {
                    errorMsg = '会话已过期，请刷新页面后重试';
                }
            } catch (e) {
                errorMsg = xhr.statusText || errorMsg;
                
                // 处理常见的HTTP状态码
                switch(xhr.status) {
                    case 0:
                        errorMsg = '网络连接错误，请检查网络';
                        break;
                    case 404:
                        errorMsg = '请求的资源不存在';
                        break;
                    case 500:
                        errorMsg = '服务器内部错误';
                        break;
                }
            }
            
            showErrorAlert(errorMsg);
        }

        function showErrorAlert(message) {
            $('#toolModal').find('.modal-body').prepend(
                `<div class="alert alert-danger">${message}</div>`
            );
        }

        function confirmDelete(toolNumber) {
            if (confirm('确定要删除该工具吗？')) {
                $.post("{% url 'tool_manage' %}", {
                    'tool_id': toolNumber,
                    'delete': true,
                    'csrfmiddlewaretoken': '{{ csrf_token }}'
                }, function () {
                    location.reload();
                });
            }
        }

        // 修改表单提交为AJAX方式
        $('[name="submitBtn"]').click(function () {
            // 清除之前的错误提示
            $('#toolForm').find('.alert-danger').remove();

            $.ajax({
                url: "{% url 'tool_manage' %}",
                type: "POST",
                data: $('#toolForm').serialize() + '&' + $(this).attr('name') + '=true',
                dataType: 'json',
                success: function (response) {
                    if (response.success) {
                        $('#toolModal').modal('hide');
                        location.reload();
                    } else {
                        // 显示表单错误
                        if (response.errors) {
                            let errors = JSON.parse(response.errors);
                            let errorHtml = '<div class="alert alert-danger">';
                            for (let field in errors) {
                                errorHtml += `<strong>${field}:</strong> ${errors[field].join(', ')}<br>`;
                            }
                            errorHtml += '</div>';
                            $('#toolForm').prepend(errorHtml);
                        } else if (response.message) {
                            $('#toolForm').prepend(
                                '<div class="alert alert-danger">' + response.message + '</div>'
                            );
                        }
                    }
                },
                error: function (xhr) {
                    let errorMsg = '操作失败';
                    try {
                        let response = JSON.parse(xhr.responseText);
                        errorMsg = response.message || errorMsg;
                    } catch (e) {
                        errorMsg = xhr.statusText || errorMsg;
                    }
                    $('#toolForm').prepend(
                        '<div class="alert alert-danger">' + errorMsg + '</div>'
                    );
                }
            });
        });

        // 确保模态框关闭事件
        $('#toolModal').on('hidden.bs.modal', function () {
            $(this).find('form')[0].reset();
        });
    </script>
{% endblock %}